package com.ruoyi.checkingin.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.checkingin.service.IERpStandardService;
import com.ruoyi.common.core.domain.e_checkingin.ERpStandard;
import com.ruoyi.common.core.domain.e_enterprise.EUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.enterprise.domain.EProfession;
import com.ruoyi.enterprise.service.IEProfessionService;
import com.ruoyi.enterprise.service.IEUserService;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.e_checkingin.ERpRecord;
import com.ruoyi.checkingin.service.IERpRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 奖惩记录Controller
 *
 * @author JYW
 * @date 2024-01-30
 */
@RestController
@RequestMapping("/checkingin/rprecord")
public class ERpRecordController extends BaseController
{
    @Autowired
    private IERpRecordService eRpRecordService;

    @Autowired
    private IERpStandardService rpStandardService;

    @Autowired
    private IEUserService userService;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private IEProfessionService professionService;

    /**
     * 查询奖惩记录列表
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(ERpRecord eRpRecord)
    {
        startPage();
        List<ERpRecord> list = eRpRecordService.selectERpRecordList(eRpRecord);
        List<ERpStandard> eRpStandards = rpStandardService.selectERpStandardList(new ERpStandard());
        List<EUser> eUsers = userService.selectEUserList(new EUser());
        List<Map<String,Object>> mapList = new ArrayList<>();
        list.forEach(eRpRecord1 -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id",eRpRecord1.getId());
            eRpStandards.forEach(eRpStandard -> {
                if (eRpRecord1.getRpId().equals(eRpStandard.getId()) ){
                    map.put("rpName",eRpStandard.getRpName());
                    map.put("rpMoney",eRpStandard.getRpType()==1?eRpStandard.getMoney():(eRpStandard.getMoney().negate()));
                }
            });
            eUsers.forEach(eUser -> {
                if (eUser.getId().equals(eRpRecord1.getuId()) ){
                    map.put("uId",eRpRecord1.getuId());
                    map.put("uName",eUser.getUserName());
                    map.put("workNumber",eUser.getWorkNumber());
                }
            });
            mapList.add(map);
        });
        return getDataTable(mapList);
    }

    /**
     * 导出奖惩记录列表
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:export')")
    @Log(title = "奖惩记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ERpRecord eRpRecord)
    {
        List<ERpRecord> list = eRpRecordService.selectERpRecordList(eRpRecord);
        ExcelUtil<ERpRecord> util = new ExcelUtil<ERpRecord>(ERpRecord.class);
        util.exportExcel(response, list, "奖惩记录数据");
    }

    /**
     * 获取奖惩记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(eRpRecordService.selectERpRecordById(id));
    }

    /**
     * 新增奖惩记录
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:add')")
    @Log(title = "奖惩记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ERpRecord eRpRecord)
    {
        return toAjax(eRpRecordService.insertERpRecord(eRpRecord));
    }

    /**
     * 修改奖惩记录
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:edit')")
    @Log(title = "奖惩记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ERpRecord eRpRecord)
    {
        return toAjax(eRpRecordService.updateERpRecord(eRpRecord));
    }

    /**
     * 删除奖惩记录
     */
    @PreAuthorize("@ss.hasPermi('checkingin:rprecord:remove')")
    @Log(title = "奖惩记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(eRpRecordService.deleteERpRecordByIds(ids));
    }

    /*查看个人本月预计工资*/
    @GetMapping("/myWage")
    public AjaxResult myWage(){
        startPage();
        Long userId = SecurityUtils.getUserId();
        Map<String,Object> map = new HashMap<>();
        //1.根据userid从职位表中获取到本月的基本工资
        SysUserPost sysUserPost = new SysUserPost();
        sysUserPost.setUserId(userId);
        this.acquireWage(map,userId);
        //2.从奖惩表中获取本人、本月受到的惩罚
        Map<String, Object> map1 = this.acquireRP(userId, new Date());
        map.put("rewords",map1.get("rewords"));
        map.put("rMoney",map1.get("rMoney"));
        //3.从奖惩表中获取本人、本月受到的奖励
        map.put("punishment",map1.get("punishment"));
        map.put("pMoney",map1.get("pMoney"));
        //4.包装数据、返回
        return AjaxResult.success(map);
    }

    /*根据userid、月份，查询员工指定月份内的工资详情*/
    public Map<String,Object> forecastWage(Long userId,Date date){
        Map<String,Object> map = new HashMap<>();
        //1.根据userid从职位表中获取到本月的基本工资
        SysUserPost sysUserPost = new SysUserPost();
        sysUserPost.setUserId(userId);
        this.acquireWage(map,userId);
        //2.从奖惩表中获取本人、本月受到的惩罚
        Map<String, Object> map1 = this.acquireRP(userId, date);
        map.put("rewords",map1.get("rewords"));
        map.put("rMoney",map1.get("rMoney"));
        //3.从奖惩表中获取本人、本月受到的奖励
        map.put("punishment",map1.get("punishment"));
        map.put("pMoney",map1.get("pMoney"));
        return map;
    }

    /**
     * 自动对当前用户的前一日考勤情况做奖惩判断
     * */
    @GetMapping("/autoSentence")
    public AjaxResult autoSentence(){
        return toAjax(eRpRecordService.autoSentence());
    }




    /*填充基本工资*/
    public  void acquireWage(Map<String,Object> map,Long userId){
        List<Long> longs = postMapper.selectPostListByUserId(userId);
        if (!longs.isEmpty()){
            String postCode = postMapper.selectPostById(longs.get(0)).getPostCode();
            EProfession profession = new EProfession();
            profession.setpNumber(postCode);
            List<EProfession> eProfessions = professionService.selectEProfessionList(profession);
            //基本工资
            map.put("fundWage",professionService.selectRespectWage(eProfessions.get(0)).get("wageSum"));
            //基本工资详情
            map.put("wageDetial",eProfessions.get(0));
        }
    }

    //2.从奖惩表中获取本人、本月受到的惩罚
    public  Map<String,Object> acquireRP(Long userId,Date date){
        Map<String,Object> map = new HashMap<>();
        List<ERpRecord> eRpRecords = eRpRecordService.selectERpRecordListByTime(userId,DateUtils.parseDateToStr("yyyy-MM",date));
        List<ERpStandard> rList = new ArrayList<>();
        List<ERpStandard> pList = new ArrayList<>();
        eRpRecords.forEach(eRpRecord -> {
            ERpStandard eRpStandard = rpStandardService.selectERpStandardById(eRpRecord.getRpId());
            eRpStandard.setCreateTime(eRpRecord.getCreateTime());
            if (eRpStandard.getRpType() == 1){
                rList.add(eRpStandard);
            }else {
                pList.add(eRpStandard);
            }
        });
        map.put("rewords",rList);
        map.put("rMoney",rList.stream()
                .map(ERpStandard::getMoney)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        map.put("punishment",pList);
        map.put("pMoney",pList.stream()
                .map(ERpStandard::getMoney)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        return map;
    }
}